package com.kchouse.homepage;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.kchouse.MainActivity;
import com.kchouse.R;
import com.kchouse.StartActivity;
import com.kchouse.bean.MerchantItem;
import com.kchouse.common.API;
import com.kchouse.common.BaseActivity;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.ToastUtils;
import com.kchouse.myadapter.HelpAdapter;
import com.kchouse.myadapter.UnionAdapter;
import com.kchouse.union.MerchantDetailsActivity;
import com.kchouse.view.ProgressView;

import java.util.ArrayList;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;
import me.fangx.haorefresh.HaoRecyclerView;
import me.fangx.haorefresh.LoadMoreListener;

public class RescueActivity extends BaseActivity implements View.OnClickListener {

    private RescueActivity mContent;
    private TextView tv_title;
    private ImageView iv_back;
    private EditText et_search;
    private HaoRecyclerView hao_recycleview;
    private int page = 1;
    private int totalCount;
    private ArrayList<MerchantItem> listmerchant = new ArrayList<>();
    private HelpAdapter helpAdapter;
    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rescue);


        mContent = this;
        intiData();
        intiView();

    }

    private void intiView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("一键施救");
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);

        View rl_search = findViewById(R.id.rl_search);
        rl_search.setOnClickListener(this);

        et_search = (EditText) findViewById(R.id.et_search);
        et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {


                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    listmerchant.clear();
                    page = 1;
                    GetHelpList(et_search.getText().toString(), page);
                    et_search.setText("");
                    hao_recycleview.setCanloadMore(false);
//                            ToastUtils.getInstanc(getActivity()).showToast("搜索");
                }
                return false;
            }
        });

        hao_recycleview = (HaoRecyclerView) findViewById(R.id.hao_recycleview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContent);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        hao_recycleview.setLayoutManager(layoutManager);
        //添加Android自带的分割线
//        hao_recycleview.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));

        //设置自定义加载中和到底了效果
        ProgressView progressView = new ProgressView(mContent);
        progressView.setIndicatorId(ProgressView.BallPulse);
        progressView.setIndicatorColor(0xff69b3e0);
        hao_recycleview.setFootLoadingView(progressView);

        helpAdapter = new HelpAdapter(mContent, listmerchant);
        hao_recycleview.setAdapter(helpAdapter);
        hao_recycleview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MerchantItem item = listmerchant.get(position);
//                        ToastUtils.getInstanc(getActivity()).showToast("商家id："+item.getId());
                intent.putExtra("Merchantid", item.getId());
                intent.setClass(mContent, MerchantDetailsActivity.class);
                startActivity(intent);
            }
        });
        hao_recycleview.setLoadMoreListener(new LoadMoreListener() {
            @Override
            public void onLoadMore() {
                new Handler().postDelayed(new Runnable() {
                    public void run() {

                        page = page + 1;
                        GetHelpList(et_search.getText().toString(), page);
                        hao_recycleview.loadMoreComplete();

                    }
                }, 2000);
            }
        });

    }


    private void intiData() {

        intent = getIntent();
        GetHelpList("", page);


    }

    private void GetHelpList(String name, int page) {
        String url = API.GethelpList;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addFormDataPart("name", name);
        params.addFormDataPart("page", page);
        params.addFormDataPart("pageSize", 10);
        params.addFormDataPart("lat", StartActivity.mLatitude + "");
        params.addFormDataPart("log", StartActivity.mLongitude + "");
        params.addFormDataPart("userId", MainActivity.userid);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    totalCount = data.getInteger("totalCount");
                    if (listmerchant.size() == totalCount)//总个数已满
                    {
                        hao_recycleview.setCanloadMore(false);
                        ToastUtils.getInstanc(mContent).showToast("暂无更多");
                    } else {
                        listmerchant.addAll(JSONObject.parseArray(data.getString("merchantList"), MerchantItem.class));
                        helpAdapter.notifyDataSetChanged();
                    }

                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.rl_search:
                listmerchant.clear();
                page = 1;
                GetHelpList(et_search.getText().toString(), page);
                et_search.setText("");
                hao_recycleview.setCanloadMore(false);
                break;
        }
    }
}
